﻿using System.Data;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System;
using stwh_Model;

namespace stwh_Common
{
    public class FormModel
    {
        /// <summary>
        /// 将stwh_FormModel泛型集合转换为指定的T对象
        /// </summary>
        /// <typeparam name="T">指代类型</typeparam>
        /// <param name="listmodel">待转换stwh_FormModel泛型集合</param>
        /// <returns></returns>
        public static T ToModel<T>(List<stwh_FormModel> listmodel)
        {
            if (listmodel.Count == 0 || listmodel == null) return default(T);
            //创建指代类型的实例
            T _t = (T)Activator.CreateInstance(typeof(T));
            //获取公共属性集合
            PropertyInfo[] propertys = _t.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                foreach (stwh_FormModel item in listmodel)
                {
                    if (pi.Name.ToLower().Equals(item.Name.ToLower()))
                    {
                        if (pi.PropertyType == typeof(int)) pi.SetValue(_t, int.Parse(item.Value), null);
                        else if (pi.PropertyType == typeof(float)) pi.SetValue(_t, float.Parse(item.Value), null);
                        else if (pi.PropertyType == typeof(double)) pi.SetValue(_t, double.Parse(item.Value), null);
                        else if (pi.PropertyType == typeof(bool)) pi.SetValue(_t, bool.Parse(item.Value), null);
                        else if (pi.PropertyType == typeof(string)) pi.SetValue(_t, item.Value, null);
                        else if (pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?))
                        {
                            if (string.IsNullOrEmpty(item.Value)) pi.SetValue(_t, null, null);
                            else pi.SetValue(_t, DateTime.Parse(item.Value), null);
                        }
                        else pi.SetValue(_t, null, null);
                        break;
                    }
                }
            }

            return _t;
        }
    }
}
